package cn.itsource.aigou.controller;

import cn.itsource.aigou.domain.ProductDoc;
import cn.itsource.aigou.repository.ProductDocRepository;
import cn.itsource.aigou.util.AjaxResult;
import cn.itsource.aigou.util.PageList;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class ProductESController {

    @Autowired
    private ProductDocRepository productDocRepository;

    /**
     * 保存一条数据
     * @param productDoc
     * @return
     */
    @PostMapping("/es/save")
    public AjaxResult save(@RequestBody ProductDoc productDoc){
        try {
            productDocRepository.save(productDoc);
            return AjaxResult.me().setSuccess(true).setMessage("成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("失败!"+e.getMessage());
        }
    }

    /**
     * 批量保存
     * @param productDocs
     * @return
     */
    @PostMapping("/es/saveBatch")
    public AjaxResult save(@RequestBody List<ProductDoc> productDocs){
        try {
            productDocRepository.saveAll(productDocs);
            return AjaxResult.me().setSuccess(true).setMessage("成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("失败!"+e.getMessage());
        }
    }

    /**
     * 删除
     * @param productId
     * @return
     */
    @DeleteMapping("/es/delete")
    public AjaxResult delete(@RequestParam("productId") Long productId){
        try {
            productDocRepository.deleteById(productId);
            return AjaxResult.me().setSuccess(true).setMessage("成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("失败!"+e.getMessage());
        }
    }

    /**
     * 批量删除
     * @param productDocs
     * @return
     */
    @DeleteMapping("/es/deleteBatch")
    public AjaxResult delete(@RequestBody List<ProductDoc> productDocs){
        try {
            productDocRepository.deleteAll(productDocs);
            return AjaxResult.me().setSuccess(true).setMessage("成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("失败!"+e.getMessage());
        }
    }

    /**
     * 高级查询
     * @param param
     * @return
     */
    @PostMapping("/es/search")
    public PageList<ProductDoc> search(@RequestBody Map<String,Object> param){
        //获取参数
        //all
        String all = (String) param.get("all");
        //page
        Integer page = (Integer) param.get("page");
        //rows
        Integer rows = (Integer) param.get("rows");
        //productTypeId
        Long productTypeId = param.get("productTypeId")!=null?(Long.valueOf((String) param.get("productTypeId"))):null;
        //brandId
        Long brandId = param.get("brandId")!=null?(Long.valueOf((String) param.get("brandId"))):null;
        //maxPrice
        Integer maxPrice = (Integer) param.get("maxPrice");
        //minPrice
        Integer minPrice = (Integer) param.get("minPrice");
        //sort
        String sort = (String) param.get("sort");
        //order
        String order = (String) param.get("order");

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //构造查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //match - all
        if(StringUtils.isNotEmpty(all))
            boolQueryBuilder.must(new MatchQueryBuilder("all",all));
        List<QueryBuilder> filter = boolQueryBuilder.filter();
        //brandId
        if(brandId!=null)
            filter.add(new TermQueryBuilder("brandId",brandId));
        //productTypeId
        if(productTypeId!=null)
            filter.add(new TermQueryBuilder("productTypeId",productTypeId));
        //range  最大价格和最小价格
        if(maxPrice!=null){
            filter.add(new RangeQueryBuilder("minPrice").lte(maxPrice));
        }
        if(minPrice!=null){
            filter.add(new RangeQueryBuilder("maxPrice").gte(minPrice));
        }

        builder.withQuery(boolQueryBuilder);
        //排序方式 order=asd desc
        SortOrder sortOrder = SortOrder.ASC;
        if("desc".equals(order)){
            sortOrder = SortOrder.DESC;
        }
        //排序 -- 根据那列排，排序方式是什么 sort=xl xp pl jg rq
        String sortColumn = "saleCount";
        if(StringUtils.isEmpty(sort)){
            sort = "xl";
        }
        switch (sort){
            case "xl":
                sortColumn = "saleCount";
                break;
            case "xp":
                sortColumn = "onSaleTime";
                break;
            case "pl":
                sortColumn = "commentCount";
                break;
            case "rq":
                sortColumn = "viewCount";
                break;
            case "jg":
                //如果是降序，则根据最高价格排序
                //如果是升序，则按照最低价格排序
                if(sortOrder == SortOrder.DESC){
                    sortColumn = "maxPrice";
                }else{
                    sortColumn = "minPrice";
                }
                break;
                default:
                    sortColumn = "saleCount";

        }
        builder.withSort(new FieldSortBuilder(sortColumn).order(sortOrder));

        //分页
        builder.withPageable(PageRequest.of(page-1, rows));

        Page<ProductDoc> iPage = productDocRepository.search(builder.build());
        return new PageList<>(iPage.getTotalElements(),iPage.getContent());

    }

}
